package com.jandan.ui.client;


import com.google.gwt.core.client.GWT;


import com.google.gwt.i18n.client.DateTimeFormat;
import com.gwtext.client.core.SortDir;
import com.gwtext.client.core.TextAlign;
import com.gwtext.client.data.DateFieldDef;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.HttpProxy;
import com.gwtext.client.data.IntegerFieldDef;
import com.gwtext.client.data.JsonReader;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.util.Format;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Component;
import com.gwtext.client.widgets.PagingToolbar;
import com.gwtext.client.widgets.ToolbarButton;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.event.PanelListenerAdapter;
import com.gwtext.client.widgets.grid.CellMetadata;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.grid.GridView;
import com.gwtext.client.widgets.grid.Renderer;
import com.gwtext.client.widgets.grid.RowParams;
import com.gwtext.client.widgets.grid.RowSelectionModel;
import com.gwtext.client.widgets.layout.FitLayout;
import com.jandan.ui.client.util.ClientUtil;

public class BrowseLearnedWordGridPanel extends GridPanel {
	// private GridPanel grid;
	private boolean showPreview = true;
	private long lessonID;
	private int libNumber;
	
	private Renderer renderWordEn = new Renderer() {
		public String render(Object value, CellMetadata cellMetadata,
				Record record, int rowIndex, int colNum, Store store) {
			// TODO Auto-generated method stub
			return record.getAsString("wordEn");
		}
	};

	private Renderer renderPhonetics = new Renderer() {
		public String render(Object value, CellMetadata cellMetadata,
				Record record, int rowIndex, int colNum, Store store) {
			// TODO Auto-generated method stub
			return Format.format("<span class='phonetics'>{1}</span>",
					new String[] { (String) value,
							record.getAsString("phonetics") });
		}
	};

	private Renderer renderWordCn = new Renderer() {
		public String render(Object value, CellMetadata cellMetadata,
				Record record, int rowIndex, int colNum, Store store) {
			// TODO Auto-generated method stub
			return record.getAsString("wordCn");
		}
	};
	
	private Renderer renderDegree = new Renderer(){
		public String render(Object value, CellMetadata cellMetadata,
				Record record, int rowIndex, int colNum, Store store) {
			// TODO Auto-generated method stub
			return ClientUtil.DEGREES[record.getAsInteger("degree")];
		}
	};
	
	private Renderer renderStartLearnedDate = new Renderer(){
		public String render(Object value, CellMetadata cellMetadata,
				Record record, int rowIndex, int colNum, Store store) {
			// TODO Auto-generated method stub
			DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
			return fmt.format(record.getAsDate("startLearnedDate"));
		}
	};
	
	private Renderer renderLatestLearnedDate = new Renderer(){
		public String render(Object value, CellMetadata cellMetadata,
				Record record, int rowIndex, int colNum, Store store) {
			// TODO Auto-generated method stub
			DateTimeFormat fmt = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
			return fmt.format(record.getAsDate("latestLearnedDate"));
		}
	};


	public BrowseLearnedWordGridPanel(long lessonID, int libNumber) {
		this.lessonID = lessonID;
		this.libNumber = libNumber;
		createComponent();
	}

	private void createComponent() {
		HttpProxy httpProxy = new HttpProxy(GWT.getModuleBaseURL()
				+ "/browserlearnedword.json?lessonID=" + lessonID + "&libNumber=" + libNumber );

		final RecordDef recordDef = new RecordDef(new FieldDef[] {
				new StringFieldDef("wordEn"), new StringFieldDef("phonetics"),
				new StringFieldDef("wordCn"),
				new IntegerFieldDef("learnedTimes"),
				new DateFieldDef("startLearnedDate"),
				new DateFieldDef("latestLearnedDate"),
				new IntegerFieldDef("degree"),
				new StringFieldDef("details") });

		JsonReader reader = new JsonReader(recordDef);		
		reader.setRoot("learnedWords");
		reader.setTotalProperty("totalCount");
		reader.setId("learnedWordID");

		final Store store = new Store(httpProxy, reader, true);
		store.setDefaultSort("wordEn", SortDir.ASC);

		ColumnConfig wordEnColumn = new ColumnConfig("英文单词", "wordEn", 120,
				false, renderWordEn, "wordEn");
		wordEnColumn.setCss("white-space:normal;");

		ColumnConfig phoneticsColumn = new ColumnConfig("音标", "phonetics", 80,
				false, renderPhonetics, "phonetics");
		phoneticsColumn.setCss("phonetics");
		phoneticsColumn.setAlign(TextAlign.CENTER);

		ColumnConfig wordCnColumn = new ColumnConfig("中文释义", "wordCn", 220,
				false, renderWordCn, "wordCn");
		wordCnColumn.setCss("white-space:normal;");
		
		ColumnConfig learnedTimesColumn = new ColumnConfig("学习次数","learnedTimes",60);
		learnedTimesColumn.setAlign(TextAlign.CENTER);

		ColumnConfig degreeColumn = new ColumnConfig("熟悉程度","degree",60,false,renderDegree,"degree");
		degreeColumn.setAlign(TextAlign.CENTER);
		
		ColumnConfig startLearnedDateColumn = new ColumnConfig("开始学习日期","startLearnedDate",120,false,renderStartLearnedDate,"startLearnedDate");
		startLearnedDateColumn.setCss("white-space:normal;");
		
		ColumnConfig latestLearnedDateColumn = new ColumnConfig("最近学习日期","latestLearnedDate",120,false,renderLatestLearnedDate,"latestLearnedDate");
		latestLearnedDateColumn.setCss("white-space:normal;");
		
		ColumnModel columnModel = new ColumnModel(new ColumnConfig[] {
				wordEnColumn, phoneticsColumn, wordCnColumn,degreeColumn,learnedTimesColumn,startLearnedDateColumn,latestLearnedDateColumn });

		columnModel.setDefaultSortable(true);
		this.setLayout(new FitLayout());
		this.setStore(store);
		this.setColumnModel(columnModel);
		this.setTrackMouseOver(false);
		this.setLoadMask(true);
		this.setSelectionModel(new RowSelectionModel());
		this.setFrame(true);
		this.setStripeRows(true);
		this.setIconCls("grid-icon");

		GridView view = new GridView() {
			public String getRowClass(Record record, int index,
					RowParams rowParams, Store store) {
				StringBuffer sb = new StringBuffer();
				if (showPreview) {
					String ss = record.getAsString("details");
					if (ss != null) {
						ss = ss.trim();
						String[] sss = ss.split("\\|");
						sb.append("<p>");
						for (int i = 0; i < sss.length; i++) {
							sb.append("{");
							sb.append(i);
							sb.append("}");
							sb.append("<br/>");
						}
						sb.append("</p>");
//						System.out.println(format);
						rowParams.setBody(Format.format(sb.toString(), sss));
					}
					return "x-grid3-row-expanded";
				} else {
					return "x-grid3-row-collapsed";
				}
			}
		};
		view.setForceFit(true);
		view.setEnableRowBody(true);
		this.setView(view);

		PagingToolbar pagingToolbar = new PagingToolbar(store);
		pagingToolbar.setPageSize(25);
		pagingToolbar.setDisplayInfo(true);
		pagingToolbar.setPrevText("上一页");
		pagingToolbar.setNextText("下一页");
		pagingToolbar.setFirstText("第一页");
		pagingToolbar.setLastText("最后一页");
		pagingToolbar.setAfterPageText("共 {0} 页");
		pagingToolbar.setBeforePageText("页");
		pagingToolbar.setRefreshText("刷新");
		pagingToolbar.setDisplayMsg("显示单词 {0} - {1} 共 {2}");
		pagingToolbar.setEmptyMsg("此小词库没有已学单词");

		pagingToolbar.addSeparator();
		ToolbarButton toolbarButton = new ToolbarButton("预览");
		toolbarButton.setPressed(showPreview);
		toolbarButton.setEnableToggle(true);
		toolbarButton.setCls("x-btn-text-icon details");
		toolbarButton.addListener(new ButtonListenerAdapter() {
			public void onToggle(Button button, boolean pressed) {
				toggleDetails(pressed);
			}
		});

		pagingToolbar.addButton(toolbarButton);
		this.setBottomToolbar(pagingToolbar);

		this.addListener(new PanelListenerAdapter() {
			public void onRender(Component component) {
				store.load(0, 25);
			}
		});
	}

	private void toggleDetails(boolean pressed) {
		showPreview = pressed;
		this.getView().refresh();
	}
}
